package com.whlilong.jxc.filemanager.editor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;

import com.whlilong.jxc.db.DbManager;
import com.whlilong.jxc.editor.support.BrandInfoEditorSupport;
import com.whlilong.jxc.listener.IEditorListener;
import com.whlilong.jxc.model.Goodsbrand;
import com.whlilong.jxc.print.IconSource;
import com.whlilong.jxc.print.PDocument;
import com.whlilong.jxc.print.PHLine;
import com.whlilong.jxc.print.PTableBoxProvider;
import com.whlilong.jxc.print.PTextBox;
import com.whlilong.jxc.print.PVSpace;
import com.whlilong.jxc.print.PrintPreview;
import com.whlilong.jxc.print.SWTPTable;
import com.whlilong.jxc.service.editor.IEditorService;
import com.whlilong.jxc.sys.ExtentionInfo;
import com.whlilong.jxc.sys.SetTableColColorListener;
import com.whlilong.jxc.treemodel.BrandInfoTreeChildren;
import com.whlilong.jxc.treemodel.BrandInfoTreeParent;
import com.whlilong.jxc.ui.provider.BrandInfoContentProvider;
import com.whlilong.jxc.ui.provider.BrandInfoLabelProvider;
import com.whlilong.jxc.ui.provider.BrandInfoTreeContentProvider;
import com.whlilong.jxc.ui.provider.BrandInfoTreeLabelProvider;
import com.whlilong.jxc.ui.sorter.BrandInfoSorter;

/**
 * 商品品牌编辑器
 * 
 * @author sjy
 * 
 */
public class BrandInfoEditor extends AbstractEditor implements IEditorService,
		IEditorListener {

	private Label infoLabel;
	private Label ppLabel;
	private Text ppbh;
	private Label ppnameLabel;
	private Text ppname;
	private Button findBt;
	protected String ppid;
	protected String brandname;
	private Table table;
	private List<Goodsbrand> list = new ArrayList<Goodsbrand>();
	protected int selItem;
	protected Text text;
	protected ExtentionInfo extentionInfo = null;
	private boolean isSave = true;

	public BrandInfoEditor() {

	}

	protected Control createGroupText(Composite parent) {
		// TODO Auto-generated method stub
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gl = new GridLayout(2, false);
		container.setLayout(gl);
		createTreeViewer(container);
		createTableViewer(container);
		return container;
	}

	private void createTableViewer(Composite parent) {
		// TODO Auto-generated method stub
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout gl = new GridLayout(4, false);
		composite.setLayout(gl);
		composite.setLayoutData(new GridData(GridData.FILL_BOTH));

		infoLabel = new Label(composite, SWT.NONE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.heightHint = 20;
		gd.horizontalSpan = 4;
		infoLabel.setLayoutData(gd);

		gd = new GridData();
		gd.widthHint = 100;
		gd.heightHint = 20;
		ppLabel = new Label(composite, SWT.RIGHT);
		ppLabel.setText("品牌编号：");
		ppLabel.setLayoutData(gd);
		ppbh = new Text(composite, SWT.BORDER);
		ppbh.setLayoutData(gd);

		ppnameLabel = new Label(composite, SWT.RIGHT);
		ppnameLabel.setText("品牌名称：");
		ppnameLabel.setLayoutData(gd);
		ppname = new Text(composite, SWT.BORDER);
		ppname.setLayoutData(gd);

		findBt = new Button(composite, SWT.NONE);
		findBt.setText("查询F7");
		findBt.setLayoutData(gd);
		findBt.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseDown(MouseEvent e) {
				// TODO Auto-generated method stub
				ppid = ppbh.getText();
				brandname = ppname.getText();
				find(ppid, brandname);
			}

		});

		tableViewer = new TableViewer(composite, SWT.BORDER | SWT.H_SCROLL
				| SWT.FULL_SELECTION);
		tableViewer.setUseHashlookup(true);

		gd = new GridData(GridData.FILL_BOTH);
		gd.horizontalSpan = 4;
		table = tableViewer.getTable();
		table.setLayoutData(gd);
		table.setToolTipText("点击单元格对数据进行修改！");
		// 设置行高
		table.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {
				event.height = 20;
			}
		});

		BrandInfoEditorSupport editingSupport = new BrandInfoEditorSupport(
				tableViewer, 1, this);
		createColumn("ID", BrandInfoSorter.ID_ASC, BrandInfoSorter.ID_DESC,
				editingSupport);

		editingSupport = new BrandInfoEditorSupport(tableViewer, 2, this);
		createColumn("品牌编号", BrandInfoSorter.sbid_asc,
				BrandInfoSorter.sbid_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new BrandInfoEditorSupport(tableViewer, 3, this);
		createColumn("商品品牌", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);

		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		// initial the tabelViewer
		tableViewer.setContentProvider(new BrandInfoContentProvider());
		tableViewer.setLabelProvider(new BrandInfoLabelProvider());
		initial();
		tableViewer.setInput(list);
		table.addListener(SWT.EraseItem, new SetTableColColorListener(table));

		table.select(0);
		table.setFocus();

	}

	@SuppressWarnings("unchecked")
	private void initial() {
		// TODO Auto-generated method stub
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_BLUE));
		infoLabel.setText("添加，删除，查询相关数据。。。");
		list = getGoodbrandinfo(null, null);
	}

	@SuppressWarnings("unchecked")
	private List getGoodbrandinfo(String id, String name) {
		// TODO Auto-generated method stub
		List<Goodsbrand> newlist = new ArrayList<Goodsbrand>();
		int[] idBuffer = { 0 };
		int[] idBuffer2 = { 0, 1 };
		Object[] idObject = { id };
		Object[] nameObject = { name };
		Object[] object = { id, name };
		if (id == null && name == null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getgoodsbrand");
		} else if (id != null && name == null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getgoodsbrandid", idBuffer, idObject);
		} else if (id == null && name != null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getgoodsbrandname", idBuffer,
					nameObject);
		} else {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getgoodsbrandinfo", idBuffer2, object);
		}
		return list=newlist;
	}

	private void createTreeViewer(Composite parent) {
		// TODO Auto-generated method stub
		treeViewer = new TreeViewer(parent, SWT.BORDER | SWT.V_SCROLL
				| SWT.FULL_SELECTION);
		treeViewer.setUseHashlookup(true);

		GridData gd = new GridData();
		gd.verticalAlignment = SWT.TOP;
		final Tree tree = treeViewer.getTree();
		tree.setLayoutData(new GridData(GridData.FILL_VERTICAL));
		final TreeColumn category = new TreeColumn(tree, SWT.LEFT);
		category.setText("商品品牌");
		category.setWidth(100);

		treeViewer.setContentProvider(new BrandInfoTreeContentProvider());
		treeViewer.setLabelProvider(new BrandInfoTreeLabelProvider());
		treeViewer.setInput(extentionInfo.getInstance().getSpbrand());

		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);

		treeViewer.expandToLevel(2);

		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				// TODO Auto-generated method stub
				IStructuredSelection selection = (IStructuredSelection) event
						.getSelection();
				if (selection.getFirstElement() instanceof BrandInfoTreeChildren) {
					BrandInfoTreeChildren ktc = (BrandInfoTreeChildren) selection
							.getFirstElement();
					String id = ktc.getGoodsbrand().getGoodsbrandid();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(getGoodbrandinfo(id, null));
				}
				if (selection.getFirstElement() instanceof BrandInfoTreeParent) {
					initial();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(list);
				}

			}
		});

	}

	// 创建工具栏

	public void print() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.onPrint();
	}

	public void refresh() {
		// TODO Auto-generated method stub
		initial();
		treeViewer.setInput(extentionInfo.getInstance().getSpbrand());
		treeViewer.expandToLevel(2);
		tableViewer.setInput(list);
	}

	public void create() {
		// TODO Auto-generated method stub
		tableViewer.getTable().setFocus();
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_BLUE));
		infoLabel.setText("提示：请点击参数单元格来添加新数据，输入完成后点击保存！");
		list = getGoodbrandinfo(null, null);
		List tableList = (List) tableViewer.getInput();
		Goodsbrand spb = new Goodsbrand();
		Goodsbrand sp = new Goodsbrand();
		if (list.size() == 0 && tableList.size()==0) {
			spb.setId(1);
			spb.setGoodsbrandid("");
			spb.setGoodsbrandname("");
			tableViewer.add(spb);
			list.add(spb);
			tableList.add(spb);
			int t = tableViewer.getTable().getItemCount();
			tableViewer.getTable().setSelection(t - 1);
		} else {
			sp = (Goodsbrand) tableList.get(tableList.size() - 1);
			if (sp.getGoodsbrandid() == null || sp.getGoodsbrandid().equals("")
					|| sp.getGoodsbrandname() == null
					|| sp.getGoodsbrandname().equals("")) {
				infoLabel.setForeground(Display.getCurrent().getSystemColor(
						SWT.COLOR_RED));
				infoLabel.setText("警告：请输入完整数据再进行添加！");
			} else {
				int id = sp.getId();
				spb.setId(id + 1);
				spb.setGoodsbrandid("");
				spb.setGoodsbrandname("");
				tableViewer.add(spb);
				list.add(spb);
				tableList.add(spb);
				int t = tableViewer.getTable().getItemCount();
				for (int i = 0; i < t; i++) {
					if (((Goodsbrand) table.getItem(i).getData()).getId() == id + 1) {
						table.select(i);
					}
				}
			}
		}
	}

	public void delete() {
		// TODO Auto-generated method stub
		IStructuredSelection selection = (IStructuredSelection) tableViewer
				.getSelection();
		Goodsbrand ks = (Goodsbrand) selection.getFirstElement();
		if (!selection.isEmpty()) {
			if (MessageDialog.openConfirm(null, "提示", "你确定删除数据吗？")) {
				delete(ks);
			}
		} else {
			MessageDialog.openConfirm(null, "提示", "请从表格中选择一行数据进行删除！");
		}
	}

	private void delete(Goodsbrand sp) {
		// TODO Auto-generated method stub
		String id = sp.getGoodsbrandid();
		if (!id.isEmpty()) {
			int[] idBuffer = { 0 };
			Object[] idObject = { id };
			List result = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getgoodsbrandid", idBuffer, idObject);
			Goodsbrand brandInfo = (Goodsbrand) result.get(0);
			DbManager.getInstance().delete(brandInfo);
		}

		refresh();
	}

	public void save() {
		// TODO Auto-generated method stub
		if (!isSave) {
			MessageDialog.openWarning(null, "提示", "数据不能保存！");
			return;
		}
		manager.notifyListener();
		Iterator data = list.iterator();
		if (!data.hasNext()) {
			MessageDialog.openWarning(null, "提示", "没有需要保存的数据！");
			return;
		}

		Job job = new Job("正在保存数据。。。") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				// TODO Auto-generated method stub
				monitor.beginTask("正在保存数据。。。", IProgressMonitor.UNKNOWN);
				for (int i = 0; i < list.size(); i++) {
					int id = list.get(i).getId();
					int[] idBuffer = { 0 };
					Object[] idObject = { id };
					List result = (List) DbManager.getInstance().search(
							"com.whlilong.jxc.ui.goodsbrand.getid", idBuffer,
							idObject);
					if (result.size() > 0) {
						String sp = list.get(i).getGoodsbrandname();
						String spid = list.get(i).getGoodsbrandid();
						if (spid != null && !spid.equals("") && sp != null
								&& !sp.equals("")) {
							int count = 0;
							Goodsbrand k = (Goodsbrand) result.get(0);
							k.setId(id);
							k.setGoodsbrandid(spid);
							k
									.setGoodsbrandname(list.get(i)
											.getGoodsbrandname());
							monitor.worked(1);
							DbManager.getInstance().update(k);
						} else {
							return Status.CANCEL_STATUS;
						}

					} else {
						String sp = list.get(i).getGoodsbrandname();
						String spid = list.get(i).getGoodsbrandid();
						if (spid != null && !spid.equals("") && sp != null
								&& !sp.equals("")) {
							Goodsbrand ks = new Goodsbrand();
							ks.setId(id);
							ks.setGoodsbrandid(spid);
							ks.setGoodsbrandname(list.get(i)
									.getGoodsbrandname());
							DbManager.getInstance().insert(ks);
						} else {

							return Status.CANCEL_STATUS;
						}

					}
				}
				monitor.done();
				return Status.OK_STATUS;
			}

		};
		job.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				final boolean isSuccess = event.getResult().isOK();
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						if (isSuccess) {

							MessageDialog.openInformation(null, "提示",
									"数据已经成功保存！");
							treeViewer.setInput(extentionInfo.getInstance()
									.getSpbrand());
							treeViewer.refresh();
							treeViewer.expandToLevel(2);

						} else
							MessageDialog.openError(null, "错误", "编号或名称为空，数据保存失败！");
					}
				});
			}
		});
		job.setUser(false);
		job.setPriority(Job.SHORT);
		job.schedule();
	}

	public void search() {
		ppid = ppbh.getText();
		brandname = ppname.getText();
		find(ppid, brandname);
	}

	private void find(String id, String name) {
		// TODO Auto-generated method stub
		if ((id == null || id.equals("")) && (name == null || name.equals(""))) {
			tableViewer.setInput(getGoodbrandinfo(null, null));
		} else if ((id != null || !id.equals(""))
				&& (name == null || name.equals(""))) {
			tableViewer.setInput(getGoodbrandinfo(id, null));
		} else if ((id == null || id.equals(""))
				&& (name != null || !name.equals(""))) {
			tableViewer.setInput(getGoodbrandinfo(null, name));
		} else {
			tableViewer.setInput(getGoodbrandinfo(id, name));
		}
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

	@Override
	public void searchByCondition() {
		search();
	}

	@Override
	public void addInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public List getList() {
		return this.list;
	}

	@Override
	public void noticeFault(String message) {
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_RED));
		infoLabel.setText(message);
		this.isSave = false;
	}

	@Override
	public void noticeSuccess() {
		infoLabel.setText("");
		this.isSave = true;
	}

	@Override
	public void preprint() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.open();
	}

}
